﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeTop.复习十月份
{
    public class Solution560
    {
        //数组里面有负数
        public int SubarraySum(int[] nums, int k)
        {
            int preSum = 0;
            int len = nums.Length;
            int count = 0;
            Dictionary<int, int> map = new Dictionary<int, int>();//存preSum和preSum的数量
            map[0] = 1;//可能从头开始
            for (int i = 0; i < len; i++)
            {
                preSum += nums[i];
                if (map.ContainsKey(preSum - k))
                {
                    count += map[preSum - k];
                }
                //检测的同时，把自己加上
                if (map.ContainsKey(preSum))
                {
                    map[preSum]++;
                }
                else
                {
                    map[preSum] = 1;
                }
            }
            return count;
        }
    }
}